package com.poker.controller;

import com.poker.consts.Consts;
import com.poker.util.Misc;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/file")
public class FileUploadController extends BaseController {

    @Value("${parentStorePath}")
    private String parentStorePath;

    @Value("${subStorePath}")
    private String subStorePath;

    @SneakyThrows(IOException.class)
    @RequestMapping(value = "upload", produces = Consts.Mapping.PRODUCES_TEXT)
    public void uploadImg(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;
        MultipartFile multFile =  multipartRequest.getFile("file");
        String filePath = multFile != null ? multFile.getOriginalFilename() : null;
        if (Misc.isEmpty(filePath)) {
            toWeb(response, "error");
            return;
        }

        String fileName = System.currentTimeMillis() + filePath.substring(filePath.lastIndexOf("."));
        String fileUrl = subStorePath + Misc.getDefDate(new Date()) + "/";
        String storePath = parentStorePath + "/" + fileUrl;

        boolean isCreate = true;
        File folder = new File(storePath);

        if (!folder.exists()) isCreate = folder.mkdirs();
        if (!isCreate) toWeb(response, "error");

        File file = new File(folder, fileName);
        multFile.transferTo(file);

        toWeb(response, fileUrl + fileName);
    }
}
